package earogya.pharmacy.patient.messages;

import java.io.IOException;
import java.util.Calendar;
import java.util.List;

import org.hibernate.HibernateException;

import ca.uhn.hl7v2.HL7Exception;
import ca.uhn.hl7v2.model.AbstractPrimitive;
import ca.uhn.hl7v2.model.DataTypeException;
import ca.uhn.hl7v2.model.Message;
import ca.uhn.hl7v2.model.Type;
import ca.uhn.hl7v2.model.v251.datatype.ST;
import ca.uhn.hl7v2.model.v251.datatype.TX;
import ca.uhn.hl7v2.model.v251.message.EQQ_Q04;
import ca.uhn.hl7v2.model.v251.message.TBR_R08;
import earogya.pharmacy.patient.PatientHibernateManager;
import earogya.pharmacy.patient.Requested_Treatments;
import earogya.pharmacy.pharmacy.PharmacyHibernateManager;
import ca.uhn.hl7v2.model.v251.segment.EQL;
import ca.uhn.hl7v2.model.v251.segment.MSH;
import ca.uhn.hl7v2.model.v251.segment.MSA;
import ca.uhn.hl7v2.model.v251.segment.QAK;
import ca.uhn.hl7v2.model.v251.segment.RDF;
import ca.uhn.hl7v2.model.v251.segment.RDT;
//import ca.uhn.hl7v2.model.v251.group.
//import ca.uhn.hl7v2.model.v251.segment.RXE;
import ca.uhn.hl7v2.model.v251.segment.MSH;


public class EQQ_Q04_Handler {
	
	private EQQ_Q04 qrymsg;
	private EQL eql= qrymsg.getEQL();
	private PatientHibernateManager hibernateManager = new PatientHibernateManager();
	private PharmacyHibernateManager phManager = new PharmacyHibernateManager();
	public EQQ_Q04_Handler(EQQ_Q04 qry){
		this.qrymsg = qry;
	}
	//eql = qrymsg.getEQL();
	public String manageMessage() throws HL7Exception, IOException{
		
		String response = null;
		if(eql.getEql1_QueryTag().getValue()== "requested_drugs")
			response = this.createResponseForRequestedDrugs();
		else
			response = this.errorInQry();
		return response;
			
	}
	
	public String createResponseForRequestedDrugs()throws HL7Exception, IOException{
		TBR_R08 msg = new TBR_R08();
		List list = null;
		
		
		String patient_id = eql.getEql4_EQLQueryStatement().getValue();
		Object[][] fieldsAndValuesRequest={{"patient_id", patient_id}};
		String[] requiredFields = {"drugId","minAmount","maxAmount","amountUnits","quantity","dosage","requestDate"};
		
		//list = hibernateManager.SQLQuery(eql.getEql4_EQLQueryStatement().getValue());
		list = hibernateManager.queryValueListFromDatabase(fieldsAndValuesRequest,requiredFields,"Requested_Treatments","request");
		
		
		MSH mshSegment = msg.getMSH();
		mshSegment.getFieldSeparator().setValue("|");
		mshSegment.getEncodingCharacters().setValue("^~\\&");
		mshSegment.getDateTimeOfMessage().getTime().setValue(Calendar.getInstance().getTime());
		mshSegment.getMessageType().getMsg1_MessageCode().setValue("TBR");
		mshSegment.getMessageType().getTriggerEvent().setValue("R08");
		
		MSA msa = msg.getMSA();
		msa.getMsa1_AcknowledgmentCode().setValue("AA");
		
		
		QAK qak = msg.getQAK();
		qak.getQak1_QueryTag().setValue(qrymsg.getEQL().getEql1_QueryTag().getValue());
		qak.getQak2_QueryResponseStatus().setValue("ok");
				
		RDF rdf = msg.getRDF();
		rdf.getRdf1_NumberOfColumnsPerRow().setValue("1");
		
		if(!list.isEmpty()){
			for(int i=0;i<list.size();i++){
				
				RDT rdt = msg.insertRDT(i);
				List list2 = null;
				TX tx = new TX(msg);
				Object[] details=(Object[])list.get(i);
				Object[][] fieldsAndValuesStore = {{"drugId", details[0]}};
				String[] name = {"name"};
				list2 = phManager.queryValueListFromDatabase(fieldsAndValuesStore,name,"Store","store");
				Object[] drugName = (Object[])list2.get(0);
				String results = (String)details[0]+"   "+(String)drugName[0]+"  "+(String)details[1]+"  "+(String)details[2]+
								"  "+(String)details[3]+"  "+(String)details[4]+"  "+(String)details[5]+"  "+(String)details[6];
				rdt.getColumnValue().setData(tx);
				tx.setValue(results);
				
			
			}
						
		}else{
			RDT rdt = msg.insertRDT(0);
			TX tx = new TX(msg);
			rdt.getColumnValue().setData(tx);
			tx.setValue("no results found");
		}
		//rdf.getRdf2_ColumnDescription(arg0)
		
		/*RDT rdt;
		for(int i=0;i<list.size();i++){
			Object[] details=(Object[])list.get(i);
			msg.insertRDT(i);
			rdt = msg.getRDT(i);
			ST st = new ST(msg);
			
			for(int j = 0; j<13;j++){
				//msg.getRDT(i).getField(j).equals((String)details[j]);
				rdt.getColumnValue().setData(st);
				st.setValue((String)details[j]);
				//rdt.getColumnValue().getExtraComponents();
				//rdt.getColumnValue().getData().getExtraComponents().getComponent(i).setData(data);
			}
		}*/
		
		//msg.getRDT().
		return msg.encode();
	}
	
	public String errorInQry() throws HL7Exception, IOException{
		TBR_R08 msg = new TBR_R08();
		
		MSH mshSegment = msg.getMSH();
		mshSegment.getFieldSeparator().setValue("|");
		mshSegment.getEncodingCharacters().setValue("^~\\&");
		mshSegment.getDateTimeOfMessage().getTime().setValue(Calendar.getInstance().getTime());
		mshSegment.getMessageType().getMsg1_MessageCode().setValue("TBR");
		mshSegment.getMessageType().getTriggerEvent().setValue("R08");
		
		MSA msa = msg.getMSA();
		msa.getMsa1_AcknowledgmentCode().setValue("AE");
		
		return msg.encode();
	}
	
	
	

}
